<template>
  <view class="container">
    <!-- 顶部签到信息 -->
    <view class="sign-header">
      <view class="sign-info">
        <text class="sign-title">每日签到</text>
        <text class="sign-days">已连续签到 {{ continuousDays }} 天</text>
      </view>
      <view class="sign-reward">
        <text class="reward-text">签到奖励</text>
        <text class="reward-desc">连续签到7天得惊喜奖励</text>
      </view>
    </view>

    <!-- 日历区域 -->
    <view class="calendar-container">
      <!-- 月份切换 -->
      <view class="month-nav">
        <text class="nav-btn" @tap="prevMonth">‹</text>
        <text class="month-title">{{ currentYear }}年{{ currentMonth }}月</text>
        <text class="nav-btn" @tap="nextMonth">›</text>
      </view>

      <!-- 星期标题 -->
      <view class="week-header">
        <text class="week-day" v-for="day in weekDays" :key="day">{{ day }}</text>
      </view>

      <!-- 日期网格 -->
      <view class="date-grid">
        <view 
          class="date-cell" 
          v-for="(date, index) in calendarDates" 
          :key="index"
          :class="{
            'current-month': date.isCurrentMonth,
            'today': date.isToday,
            'signed': date.isSigned,
            'disabled': !date.isCurrentMonth
          }"
          @tap="handleDateClick(date)"
        >
          <text class="date-num">{{ date.day }}</text>
          <text class="sign-dot" v-if="date.isSigned && date.isCurrentMonth">✓</text>
        </view>
      </view>
    </view>

    <!-- 签到按钮 -->
    <view class="sign-btn-container">
      <button 
        class="sign-btn" 
        :class="{ 'signed': todaySigned }" 
        :disabled="todaySigned"
        @tap="handleSign"
      >
        {{ todaySigned ? '今日已签到' : '立即签到' }}
      </button>
    </view>

    <!-- 签到成功提示 -->
    <view class="sign-success" v-if="showSuccess">
      <view class="success-content">
        <text class="success-title">签到成功!</text>
        <text class="success-desc">积分 +{{ signPoints }}</text>
        <text class="success-tip">已连续签到 {{ continuousDays }} 天</text>
        <button class="close-btn" @tap="showSuccess = false">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      signedDates: [], // 已签到的日期数组
      continuousDays: 0, // 连续签到天数
      todaySigned: false, // 今天是否已签到
      showSuccess: false, // 显示签到成功提示
      signPoints: 5 // 签到积分
    }
  },
  computed: {
    // 生成日历日期数组
    calendarDates() {
      const year = this.currentYear
      const month = this.currentMonth
      
      // 当月第一天
      const firstDay = new Date(year, month - 1, 1)
      // 当月最后一天
      const lastDay = new Date(year, month, 0)
      // 当月第一天是星期几
      const firstDayWeek = firstDay.getDay()
      // 当月总天数
      const daysInMonth = lastDay.getDate()
      
      // 上个月最后几天
      const prevMonthLastDay = new Date(year, month - 1, 0).getDate()
      // 下个月前几天
      const nextMonthFirstDay = new Date(year, month, 1).getDay()
      
      const dates = []
      
      // 添加上个月末尾的日期
      for (let i = firstDayWeek - 1; i >= 0; i--) {
        const day = prevMonthLastDay - i
        dates.push({
          day,
          isCurrentMonth: false,
          isToday: false,
          isSigned: this.isDateSigned(year, month - 1, day),
          date: new Date(year, month - 2, day)
        })
      }
      
      // 添加当月日期
      const today = new Date()
      for (let i = 1; i <= daysInMonth; i++) {
        const isToday = today.getFullYear() === year && 
                        today.getMonth() + 1 === month && 
                        today.getDate() === i
        dates.push({
          day: i,
          isCurrentMonth: true,
          isToday,
          isSigned: this.isDateSigned(year, month, i),
          date: new Date(year, month - 1, i)
        })
      }
      
      // 添加下个月开始的日期
      const totalCells = 42 // 6行7列
      const remainingCells = totalCells - dates.length
      for (let i = 1; i <= remainingCells; i++) {
        dates.push({
          day: i,
          isCurrentMonth: false,
          isToday: false,
          isSigned: this.isDateSigned(year, month + 1, i),
          date: new Date(year, month, i)
        })
      }
      
      return dates
    }
  },
  mounted() {
    this.loadSignData()
  },
  methods: {
    // 加载签到数据
    loadSignData() {
      // 从本地存储获取签到数据
      try {
        const signData = uni.getStorageSync('signData') || {}
        this.signedDates = signData.signedDates || []
        this.continuousDays = signData.continuousDays || 0
        
        // 检查今天是否已签到
        const today = new Date()
        const todayStr = this.formatDate(today)
        this.todaySigned = this.signedDates.includes(todayStr)
      } catch (e) {
        console.error('加载签到数据失败:', e)
      }
    },
    
    // 检查指定日期是否已签到
    isDateSigned(year, month, day) {
      const dateStr = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
      return this.signedDates.includes(dateStr)
    },
    
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 上个月
    prevMonth() {
      if (this.currentMonth === 1) {
        this.currentMonth = 12
        this.currentYear--
      } else {
        this.currentMonth--
      }
    },
    
    // 下个月
    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentMonth = 1
        this.currentYear++
      } else {
        this.currentMonth++
      }
    },
    
    // 处理日期点击
    handleDateClick(date) {
      if (!date.isCurrentMonth) return
      
      // 可以添加查看某天签到状态的逻辑
      console.log('点击日期:', date)
    },
    
    // 处理签到
    handleSign() {
      if (this.todaySigned) return
      
      const today = new Date()
      const todayStr = this.formatDate(today)
      
      // 添加到已签到数组
      this.signedDates.push(todayStr)
      this.todaySigned = true
      
      // 计算连续签到天数
      this.calculateContinuousDays()
      
      // 保存到本地存储
      this.saveSignData()
      
      // 显示签到成功提示
      this.showSuccess = true
      
      // 模拟API调用
      this.submitSignToServer()
    },
    
    // 计算连续签到天数
    calculateContinuousDays() {
      let continuous = 1
      const today = new Date()
      
      // 从昨天开始往前检查
      for (let i = 1; i <= 30; i++) {
        const checkDate = new Date(today)
        checkDate.setDate(today.getDate() - i)
        const checkDateStr = this.formatDate(checkDate)
        
        if (this.signedDates.includes(checkDateStr)) {
          continuous++
        } else {
          break
        }
      }
      
      this.continuousDays = continuous
    },
    
    // 保存签到数据到本地存储
    saveSignData() {
      try {
        const signData = {
          signedDates: this.signedDates,
          continuousDays: this.continuousDays
        }
        uni.setStorageSync('signData', signData)
      } catch (e) {
        console.error('保存签到数据失败:', e)
      }
    },
    
    // 提交签到到服务器（模拟）
    submitSignToServer() {
      // 实际项目中这里应该调用API
      console.log('提交签到数据:',this.signedDates)
      
      // 模拟API调用
      // setTimeout(() => {
      //   console.log('签到成功，服务器已记录')
      // }, 500)
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  /* background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%); */
  /* min-height: 100vh; */
  color: #333;
}

/* 顶部签到信息 */
.sign-header {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
}

.sign-info {
  display: flex;
  flex-direction: column;
}

.sign-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.sign-days {
  font-size: 26rpx;
  color: #666;
}

.sign-reward {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.reward-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 5rpx;
}

.reward-desc {
  font-size: 22rpx;
  color: #999;
}

/* 日历容器 */
.calendar-container {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
}

/* 月份导航 */
.month-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.nav-btn {
  font-size: 40rpx;
  color: #6a11cb;
  padding: 10rpx 20rpx;
}

.month-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 星期标题 */
.week-header {
  display: flex;
  margin-bottom: 20rpx;
}

.week-day {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
}

/* 日期网格 */
.date-grid {
  display: flex;
  flex-wrap: wrap;
}

.date-cell {
  width: 14.28%;
  aspect-ratio: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  margin-bottom: 10rpx;
}

.date-num {
  font-size: 28rpx;
  color: #333;
}

.date-cell.disabled .date-num {
  color: #ccc;
}

.date-cell.today .date-num {
  color: #fff;
  /* background: #ff6b6b; */
  background: rgb(67, 147, 244);
  color: #fff !important;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.date-cell.signed .date-num {
  color: #6a11cb;
  font-weight: bold;
}

.sign-dot {
  position: absolute;
  bottom: 5rpx;
  font-size: 20rpx;
  color: #6a11cb;
}

/* 签到按钮 */
.sign-btn-container {
  padding: 20rpx;
}

.sign-btn {
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  color: white;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: bold;
  height: 90rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 10rpx 20rpx rgba(255, 107, 107, 0.3);
}

.sign-btn.signed {
  background: #e0e0e0;
  color: #999;
  box-shadow: none;
}

/* 签到成功提示 */
.sign-success {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.success-content {
  background: white;
  width: 80%;
  border-radius: 20rpx;
  padding: 50rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.success-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #6a11cb;
  margin-bottom: 20rpx;
}

.success-desc {
  font-size: 32rpx;
  color: #ff6b6b;
  margin-bottom: 15rpx;
}

.success-tip {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 40rpx;
}

.close-btn {
  background: #6a11cb;
  color: white;
  border-radius: 50rpx;
  width: 200rpx;
  font-size: 28rpx;
}
</style>